package main.java.com.waylau.netty.demo.privateprotocol.client;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import main.java.com.waylau.netty.demo.privateprotocol.struct.Header;
import main.java.com.waylau.netty.demo.privateprotocol.struct.NettyMessage;
import main.java.com.waylau.netty.demo.privateprotocol.util.MessageType;
import com.alibaba.fastjson.JSON;

/**
 * @author Lilinfeng
 * @date 2014年3月15日
 * @version 1.0
 */
public class LoginAuthReqHandler extends SimpleChannelInboundHandler<Object> {
	/**
	 * 连接成功 先发送一个 认证请求
	 */
	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		ctx.writeAndFlush(JSON.toJSONString(buildLoginReq()));
	}

	@Override
	public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
		NettyMessage message = JSON.parseObject((String) msg, NettyMessage.class);
		// 如果是握手应答消息，需要判断是否认证成功
		if (message.getHeader() != null && message.getHeader().getType() == MessageType.LOGIN_RESP.value()) {
			int loginResult = (int) message.getBody();
			if (loginResult != 0) {
				// 握手失败，关闭连接
				ctx.close();
			} else {
				System.out.println("Login is ok : " + message);
				ctx.fireChannelRead(msg);
			}
		} else {
			ctx.fireChannelRead(msg);
		}
	}

	private NettyMessage buildLoginReq() {
		NettyMessage message = new NettyMessage();
		Header header = new Header();
		header.setType(MessageType.LOGIN_REQ.value());
		message.setHeader(header);
		return message;
	}

	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		ctx.fireExceptionCaught(cause);
	}
}
